#include "bsp_task.h"
#include "bsp_key.h"
#include "gpio.h"
#include "delay.h"
#include "app_cfg.h"
#include "os_cfg.h"
#include "stm32f1xx_hal.h"
#include "ucos_ii.h"
#include "itoa.h"

OS_STK LED0_TASK_STK[LED0_STK_SIZE];
OS_STK LED1_TASK_STK[LED1_STK_SIZE];
OS_STK KEY_SCAN_TASK_STK[KEY_SCAN_STK_SIZE];
OS_STK LCD_TASK_STK[LCD_STK_SIZE];
uint8_t err = 0;
extern uint8_t num;
OS_STK_DATA stk_data;
/**
 * @brief LED0 task
 * @retval None
 */
void LED0_Task(void *p_arg)
{
    
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    __HAL_RCC_GPIOB_CLK_ENABLE();
    GPIO_InitStruct.Pin = LED0_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(LED0_GPIO_Port, &GPIO_InitStruct);
    HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000);
    while (1)
    {
        HAL_GPIO_TogglePin(LED0_GPIO_Port, LED0_Pin);
        err = OSTaskStkChk(8, &stk_data);
        OSTimeDly(500);

    }
}

/**
 * @brief LED1 task
 * @retval None
 */
void LED1_Task(void *p_arg)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    __HAL_RCC_GPIOC_CLK_ENABLE();
    GPIO_InitStruct.Pin = LED1_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(LED1_GPIO_Port, &GPIO_InitStruct);
    while (1)
    {
        HAL_GPIO_TogglePin(LED1_GPIO_Port, LED1_Pin);
        err = OSTaskStkChk(7, &stk_data);
        OSTimeDly(100);
    }
}

void LCD_Task(void *p_arg)
{
    char numChar[2] = {0};
    while(1)
    {
        itoa(num, numChar);
        ST7735S_DrawFont_GBK16(0, 0, YELLOW, BLUE, (uint8_t *)numChar);
        OSTimeDly(30);
    }
}


void Task_Init(void)
{
    
    OSInit();
    
    OSTaskCreateExt(LED0_Task, (void *)0, &LED0_TASK_STK[LED0_STK_SIZE - 1],
                    LED0_TASK_PRIO, LED0_TASK_PRIO,
                    &LED0_TASK_STK[0], LED0_STK_SIZE, (void *)0, OS_TASK_OPT_STK_CHK);

    OSTaskCreateExt(LED1_Task, (void *)0, &LED1_TASK_STK[LED1_STK_SIZE - 1],
                    LED1_TASK_PRIO, LED1_TASK_PRIO,
                    &LED1_TASK_STK[0], LED1_STK_SIZE, (void *)0, OS_TASK_OPT_STK_CHK);

    OSTaskCreateExt(Key_Task, (void *)0, &KEY_SCAN_TASK_STK[KEY_SCAN_STK_SIZE - 1],
                   KEY_SCAN_TASK_PRIO, KEY_SCAN_TASK_PRIO,
                   &KEY_SCAN_TASK_STK[0], KEY_SCAN_STK_SIZE, (void *)0, OS_TASK_OPT_STK_CHK);

    OSTaskCreateExt(LCD_Task, (void *)0, &LCD_TASK_STK[LCD_STK_SIZE - 1],
                    LCD_TASK_PRIO, LCD_TASK_PRIO,
                    &LCD_TASK_STK[0], LCD_STK_SIZE, (void *)0, OS_TASK_OPT_STK_CHK);
    OSStart();
}
